/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package window;

/**
 * @author z00611952
 * @since 2021/9/21
 */
public class leetcode206_minSubArrayLen {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {2,3,1,2,4,3};
        System.out.println(solution.minSubArrayLen(7, nums));
    }
}

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0, right = 0;
        int valid = 0;
        int len = Integer.MAX_VALUE;
        int sum = 0;
        while(right < nums.length){
            int num = nums[right];
            right++;
            sum += num;
            if(sum >= target){
                valid++;
            }

            while(valid > 0){
                // 更新
                if(right - left < len){
                    len = right - left;
                }
                // 开始缩小
                int lnum = nums[left];
                left++;
                if(sum - lnum < target){
                    valid--;
                }
                sum -= lnum;
            }
        }
        return len == Integer.MAX_VALUE ? 0: len;
    }
}
